package com.zxc.listener;

import com.zxc.bootquartz.QuartzJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class QuartzApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private Scheduler scheduler;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        try {
            TriggerKey triggerKey1 = TriggerKey.triggerKey("trigger1", "group1");
            Trigger trigger1 = scheduler.getTrigger(triggerKey1);
            if (trigger1 == null) {
                trigger1 = TriggerBuilder.newTrigger()
                        .withIdentity(triggerKey1)
                        .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
                        .startNow()
                        .build();
            }
            JobDetail jobDetail1 = JobBuilder.newJob(QuartzJob.class)
                    .withIdentity("job1", "group1")
                    .build();
            scheduler.scheduleJob(jobDetail1, trigger1);

            TriggerKey triggerKey2 = TriggerKey.triggerKey("trigger2", "group2");
            Trigger trigger2 = scheduler.getTrigger(triggerKey2);
            if (trigger2 == null) {
                trigger2 = TriggerBuilder.newTrigger()
                        .withIdentity(triggerKey2)
                        .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
                        .startNow()
                        .build();
            }
            JobDetail jobDetail2 = JobBuilder.newJob(QuartzJob.class)
                    .withIdentity("job2", "group2")
                    .build();
            scheduler.scheduleJob(jobDetail2, trigger2);


            TriggerKey triggerKey3 = TriggerKey.triggerKey("trigger3", "group3");
            Trigger trigger3 = scheduler.getTrigger(triggerKey3);
            if (trigger3 == null) {
                trigger3 = TriggerBuilder.newTrigger()
                        .withIdentity(triggerKey3)
                        .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
                        .startNow()
                        .build();
            }
            JobDetail jobDetail3 = JobBuilder.newJob(QuartzJob.class)
                    .withIdentity("job3", "group3")
                    .build();

            scheduler.scheduleJob(jobDetail3, trigger3);

            scheduler.start();


        } catch (SchedulerException e) {
            e.printStackTrace();
        }

    }
}
